# 此函数用来导入route_dist.csv和new_OP_1.csv的数据，即各网点间的距离矩阵，网点经纬度坐标
import argparse
import datetime
import os

import numpy as np
import pandas as pd

from args import get_args_parser
from tools.BDgetDist.getDist import cal_route


class VRPTWLoadData():

    def __init__(self, args, DATA_PATH=None):

        if DATA_PATH is None:
            self.DATA_PATH = os.path.join(os.getcwd(), 'DATA/vrptw_opt/')
        else:
            self.DATA_PATH = DATA_PATH
        print("路径：", self.DATA_PATH)
        self.device = pd.read_csv(os.path.join(self.DATA_PATH, 'device_info_1.csv'), encoding='gbk').values
        FT = np.array(list(map(lambda x: datetime.datetime.strptime(x.strip(), '%H:%M:%S'), self.device[:, 7])))
        QT = np.array(list(map(lambda x: datetime.datetime.strptime(x.strip(), '%H:%M:%S'), self.device[:, 6])))

        location = self.device[:, 3:5].astype(np.float32)
        # location[:, 0], location[:, 1] = self.standardization(location[:, 0]), self.standardization(location[:, 1])

        self.QT = np.array(list(map(lambda x: (x - QT[0]).seconds / 60, QT))).astype(np.float32)
        self.FT = np.array(list(map(lambda x: (x - QT[0]).seconds / 60, FT))).astype(np.float32)
        self.ST = self.device[:, 5].astype(np.float32)
        self.location = location

        try:
            self.route_dist = np.array([
                pd.read_csv(os.path.join(self.DATA_PATH, 'route_dist_%d.csv' % (i)), encoding='utf-8', dtype=float,
                            header=None).values for i in [0, 1, 2, 3, 4]])
            self.route_time = np.array([
                pd.read_csv(os.path.join(self.DATA_PATH, 'route_time_%d.csv' % (i)), encoding='utf-8', dtype=float,
                            header=None).values for i in [0, 1, 2, 3, 4]])
        except UnicodeDecodeError:
            assert False, "请确认route_dist_?.csv是否使用了UTF-8编码"
        except FileNotFoundError:
            self.route_dist, self.route_time = cal_route(args, location)
            df1 = pd.DataFrame(self.route_arr)
            df1.values /= 1000.
            df1.to_csv(os.path.join(self.DATA_PATH, 'route_dist.csv'), header=False, index=False)
            df2 = pd.DataFrame(self.time_arr)
            df2.values /= 60.
            df2.to_csv(os.path.join(self.DATA_PATH, 'route_time.csv'), header=False, index=False)
        finally:
            self.route_time = np.pad(self.route_time, [(0, 1), (0, 0,), (0, 0)], 'mean').astype(np.float32)
            self.route_dist = np.pad(self.route_dist, [(0, 1), (0, 0,), (0, 0)], 'mean').astype(np.float32)

    @staticmethod
    def normalization(data):
        _range = np.max(data) - np.min(data)
        return (data - np.min(data)) / _range

    @staticmethod
    def standardization(data):
        mu = np.mean(data, axis=0)
        sigma = np.std(data, axis=0)
        return (data - mu) / sigma


if __name__ == '__main__':
    # 测试导入数据函数
    parser = argparse.ArgumentParser('DeiT training and evaluation script', parents=[get_args_parser()])
    args = parser.parse_args()
    data = VRPTWLoadData(args)
    print(data.route_dist)
    print(data.location)
